/*
 * @Descripttion: 
 * @version: 1.0
 * @Author: zhangti
 * @Date: 2020-01-14 10:30:23
 * @LastEditors  : sueRimn
 * @LastEditTime : 2020-01-15 13:59:03
 */
/**
 * 测控分析
 * 分析导弹经过雷达监控范围
 * 计算开始点和结束点
 */

import Analyser from './analyser.js';
import config from './config.js';
export default class PassAnalyze extends Analyser{
    /**
	 * 初始化
	 * @param {*} supers 
	 * @param {*} opt
	 */
	constructor(supers,opt){
		super(supers);
		//opt = Cesium.defaultValue(opt, Cesium.defaultValue.EMPTY_OBJECT);	//判断是否有值
		this.opt = opt;
		this.analyser();
	}
	/**
	 * 创建分析
	 */
	analyser(){
        if (!Cesium.defined(this._viewer)) {
            throw new Cesium.DeveloperError('viewer is required.');
        }
        if(!this.opt){
            return false;
        }
		this.passPrototype = new PassPrototype(this);
	}
    
}
/**
 * 过境分析类
 */
class PassPrototype{
    constructor(_that){
		this._that = _that;
		this.options = _that.opt;
		this.viewer = _that._viewer;
        this.entitys = _that.entitys;
        this.tools = _that.Tools;
        this.mouseManager = _that.mouseManager;

        this._passEntity = [];
        this._radars = [];
        this._interPoints = [];
        this._groundPonit = [];
        this._sateLine = [];
        this.czmlDataSource = null;
        this.analyzeResult = null;
        //地面测试点
        this.groundPoint = [
            {name:"测试站No.1",lat: 42.414136487719354, lon: 100.52056873233481, alt: 0,scope:400},
            {name:"测试站No.2",lat: 42.42522146204617, lon: 109.85947530942975, alt: 0,scope:2200},
            {name:"测试站No.3",lat: 33.1819896042328, lon: 109.5591230090901, alt: 0,scope:280},
            {name:"测试站No.4",lat: 32.019262705194734, lon: 101.73699414432289, alt: 0,scope:1000},
            {name:"测试站No.5",lat: 27.496123837273654, lon: 103.82420725508969, alt: 0,scope:2000},
            {name:"测试站No.6",lat: 26.949808853110465, lon: 114.53228575748204, alt: 0,scope:1200},
            {name:"测试站No.7",lat: 35.685974970635534, lon: 93.2030228474047, alt: 0,scope:600},
            {name:"测试站No.8",lat: 24.73499910338626, lon: 106.24244324184826, alt: 0,scope:800},
            {name:"测试站No.9",lat: 41.73492679655367, lon: 121.17656582042726, alt: 0,scope:1000}
        ]
		this.load();
    }
    //加载数据
    load(){
        if(!this.options.data){
            return false;
        }
        this.parseCzml(this.options.data.czml);


    }
    //解析czml
    parseCzml(czml){
        let newCzml = czml.replace(/[\n\r]/g, '');
        Cesium.CzmlDataSource.load(JSON.parse(newCzml)).then((dataSource) => {
            this.czmlDataSource = dataSource;
            this.viewer.clock.shouldAnimate = true;
            this.viewer.clock.multiplier = 120;
            if (dataSource.entities._entities._array.length == 0) {
                alert("未获取到实体信息")
                return false;
            }
            let czmlLine = [];
            //存储卫星轨迹
            for (let i in dataSource.entities._entities._array) {
                let sateEntity = dataSource.entities._entities._array[i],
                    sate_position = sateEntity.position._property._values,
                    satePostionMsg = this.tools.dataCluster(sate_position, 3),
                    positions = []; //三个一组
                for (let ii in satePostionMsg) { //转成可用的position
                    positions.push({
                        x: satePostionMsg[ii][0],
                        y: satePostionMsg[ii][1],
                        z: satePostionMsg[ii][2]
                    });
                }
                czmlLine.push(positions);
            }
            //获取所有雷达点
            this.parseGroundPoint().then((res)=>{
                //添加完设备探测范围后回调 开始计算分析
                this.compute(czmlLine, (obj) => { 
                    //分析结果
                    this.analyzeResult = obj;
                    //创建虚线
                    for(let i in czmlLine){
                        let line = this.entitys.createLine(czmlLine[i],'轨迹线' ,new Cesium.PolylineDashMaterialProperty({
                            color: Cesium.Color.RED
                        }));
                        this._sateLine.push(line);
                    }
                    //创建树
                    //this.createNodeTree()
                    this.viewer.dataSources.add(this.czmlDataSource);
                });
             });
        });
    }
    /**
     * 解析站点和雷达
     */
    parseGroundPoint(){
        let $this = this;
        //创建雷达
        function createRadar(dentity){
            let rentity = $this.entitys.createEntity();
            rentity.name = dentity.name;
            rentity.position = dentity.position;
            rentity.ellipsoid = $this.entitys.getEllipsoid({
                r: dentity.scope * 1000
            });
            rentity.ide = "ellipsoid";
            rentity.pid = dentity.id;
            $this._radars.push($this.entitys.add(rentity));
        }
        //创建地面点
        function createGroundPoint(items){
            let dentity = $this.entitys.createEntity();
            dentity.name = items.name;
            dentity.position = Cesium.Cartesian3.fromDegrees(items.lon, items.lat, items.alt)
            dentity.label = $this.entitys.getLabel(items.name);
            dentity.billboard = $this.entitys.getBillboard(config.STATICDIR +'/Cesium/Apps/SampleData/kml/facilities/GroundStation.png');
            dentity.scope = items.scope;

            let dentityObj = $this.entitys.add(dentity);
            $this._groundPonit.push(dentityObj);
            
            return dentityObj;
        }
        return new Promise((resolve, reject)=>{
            
            if(this.groundPoint.length == 0)return false;
            for(let i in this.groundPoint){
                let items = this.groundPoint[i];
                createRadar(createGroundPoint(items));
            }
            resolve();
        })
    }
    //创建
    createData(interPoints){
        console.log('-- 计算完成,重新绘制 --');
        //清除所有雷达
        for (let i in this._radars) {
            this.entitys.remove(this._radars[i]);
        }
        for (let i in this._groundPonit) {
             this.entitys.remove(this._groundPonit[i]);
        }
        if(interPoints.length > 0){
            //添加雷达范围
            for(let i in interPoints){
                this._passEntity.push(this.entitys.add(interPoints[i][0].object.id));
            }
            //添加地面设备
            for(let i in interPoints){
                for (let j in this._groundPonit) {
                    if(interPoints[i][0].object.id.pid == this._groundPonit[j].id){
                        this._passEntity.push(this.entitys.add(this._groundPonit[j]));
                        break;
                    }
                }
            }
        }
        this._radars = []; //清除所有设备 重新绘制
        this._groundPonit = [];
    }
    //解析数据
    parseData(radarInterLine, DandaoLine, call){
        console.log('-- 计算中 --');
        let $this = this;
        try {
            if(radarInterLine.length > 0){
                //处理所有相交点
                const interPoints = this.tools.groupBy(radarInterLine,function(item){
                    return [item.pid]
                });
                 //创建相交线
                 function createInterPoint(startPoint,endPoint){
                    let start_position,end_position,distance;
                    if(endPoint == undefined){
                        //endPoint = maps.mouseManager.worldToLonlat(endPoint);
                        end_position = DandaoLine[DandaoLine.length - 1];
                    }else{
                        end_position = endPoint.position//Cesium.Cartesian3.fromDegrees(endPoint.x,endPoint.y,endPoint.z);   
                    }
                    start_position = startPoint.position;//Cesium.Cartesian3.fromDegrees(startPoint.x,startPoint.y,startPoint.z);
                    distance = $this.tools._distance(start_position,end_position); //距离

                    let pentity= $this.entitys.createPoint(start_position, '起点: '+  startPoint.object.id.name +'\n' + '距离: ' + (distance / 1000).toFixed(3)  +'公里\n', true);
                    pentity.name = startPoint.object.id.name;
                    pentity.oid = startPoint.id;
                    $this._passEntity.push(pentity);

                    //创建终点
                    if(endPoint != undefined){ //默认最后一个 不创建
                        let pentity2 = $this.entitys.createPoint(end_position, '终点: '+  endPoint.object.id.name +'\n', true);
                        pentity2.name =  endPoint.object.id.name;
                        pentity2.oid = endPoint.id;
                        $this._passEntity.push(pentity2);
                    }
                    //创建线
                // maps.entitys.createLine([start_position,end_position],start_position.id);
                }

                //剔除近似点
                function boolValue(items){
                    let newItems = [] ,startItems = [],stopItems = [];
                    let lonlat = $this.mouseManager.worldToLonlat(items[0].position);
                    for (let i = 0; i < items.length; i++) {
                        let lonlat_i = $this.mouseManager.worldToLonlat(items[i].position);
                        if(Math.abs(lonlat.lat - lonlat_i.lat) < 0.1 ){ //偏差
                            items[i].height = lonlat_i.alt;
                            items[i].lon = lonlat_i.lon;
                            items[i].lat = lonlat_i.lat;
                            startItems.push(items[i]);
    
                        }else{
                            items[i].height = lonlat_i.alt;
                            items[i].lon = lonlat_i.lon;
                            items[i].lat = lonlat_i.lat;
                            stopItems.push(items[i]);
                        }
                    }
                    //最小高度
                    let startMinHeight = Math.min.apply(Math, startItems.map(function(item) {
                        return item.height
                    })),stopMinHeight = Math.min.apply(Math, stopItems.map(function(item) {
                        return item.height
                    }));
                    startItems.map(function(item) {
                        if(startMinHeight == item.height){
                            newItems[0] = item;
                        }
                    }), stopItems.map(function(item) {
                        if(stopMinHeight == item.height){
                            newItems[1] = item;
                        }
                    })
                    console.log(newItems);
                    return newItems;
                }
                for(let i in interPoints){
                    //只有一个的
                    if(interPoints[i].length == 1){
                        //直接取第一个
                        createInterPoint(interPoints[i][0])
                    }else if(interPoints[i].length >= 2){
                        //判断经纬度偏差 是否近似点
                            let items = interPoints[i];
                            items = boolValue(items)
                            if(items.length == 1){ //判断是否有终点
                                createInterPoint(items[0])
                            }else{
                                if(items.length == 2){
                                    createInterPoint(items[0],items[1])
                                }else{
                                    createInterPoint(items[0],items[items.length - 1])
                                    console.log(items);
                                }
                            }
                        }
                }
                call(interPoints);
            }else{
                alert("相交点为空");
                return false;
            }
            
        } catch (error) {
           console.log(error); 
        }
    }
    /** 
     * 分析相交点
    */
   analyzeInter(sateValue){
        return new Promise((resolve, reject)=>{
            let radarLine = [];
            //计算线到
            for (let i = 0; i < sateValue.length; i++) { //计算 每一组坐标和一个雷达的相交
                if (sateValue[i].x == 0 | sateValue[i].y == 0) continue;
                if (!sateValue[i + 1]) continue;
                let interPoint = this._that.getIntersectObj(sateValue[i], sateValue[i + 1], [], false);
                if (interPoint.length > 0) {
                    for (let i in interPoint) {
                        if (interPoint[i].object) {
                            if (interPoint[i].object.id.ide == "ellipsoid") {
                                interPoint[i].pid = interPoint[i].object.id.pid; //提取id
                                radarLine.push(interPoint[i]);
                            }
                        }
                    }
                }
            }
            resolve(radarLine);
        });
       
    }
    /**
     * 计算
     */
    compute(satesLine,call){
        if(satesLine.length == 0){
            return false;
        }
        //延时防止雷达没有绘制结束
        setTimeout(() => {
            //异步策咯
            new Promise((resolve, reject) => {
                for (let i in satesLine) { //卫星
                    let sate = satesLine[i];
                    if (sate.length > 0) {
                        this.analyzeInter(sate).then((radarInterLine)=>{
                            this.parseData(radarInterLine,sate,(interPoints)=>{



                                let startPonint = this.entitys.createPoint(sate[0], '起点', true);
                                let stopPonint = this.entitys.createPoint(sate[sate.length -1], '终点', true);
                                //结果
                                if(i == satesLine.length-1){
                                    this.createData(interPoints);
                                    resolve(interPoints);
                                }  
                            })
                        });
                    }
                }
            }).then((res) =>{
                call(res);
            });

        },2000);
    }
    /**
     * 创建节点控制
     */
    createNodeTree(nodes){
        let Options = function () {
           for(let key in nodes){
                this[key] = nodes[key];
           }
        }
        let option = new Options();
        let gui = new dat.GUI();
        gui.__closeButton.innerHTML = "收缩面板";

        for(let key in nodes){
            gui.add(option, key).name(nodes[key].name).onChange(function (value) {
                for(let i in this._passEntity){
                    if(this._passEntity[i].pid){

                    }
                }
            })
       }
    }
}